package com.khotyn.heresy.validator;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

import com.khotyn.heresy.bean.UserLogin;
import com.khotyn.heresy.dao.UserDAO;
import com.khotyn.heresy.util.MD5Util;

/**
 * 登录信息的验证器
 * 
 * @author 王长乐
 * 
 */
public class LoginValidator implements Validator {
	private UserDAO userDAO; // 相册DAO

	public boolean supports(Class arg0) {

		return UserLogin.class.equals(arg0);
	}

	public void validate(Object command, Errors errors) {

		UserLogin userLogin = (UserLogin) command;
		// 验证细节待讨论
		ValidationUtils.rejectIfEmpty(errors, "email",
				"User email is required.");
		ValidationUtils.rejectIfEmpty(errors, "password",
				"password is required.");

		String passwd = MD5Util
				.EncoderByMd5(userLogin.getPassword().getBytes());

		UserLogin user = new UserLogin();
		user = userDAO.selectLoginInfoByEmail(userLogin.getEmail());

		if (user == null || !passwd.equals(user.getPassword())) {
			errors.rejectValue("email", "error.not match",
					"There is a error in email or password!");
		}

	}

	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;
	}

}
